#include "httpserver.h"

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QStringList>
#include <QString>
#include <QDateTime>
#include <QFile>


#include "httpclient.h"

HttpServer::HttpServer(int port, QObject *parent) : Server(port, parent)
{
}




void HttpServer::processRequest(HttpRequest request)
{
    HttpClient *client = static_cast<HttpClient*>(sender());

    QString content = request.content();
    //qDebug() << port() << " === " <<  content << "\n\n";


    QStringList tokens = content.split(QRegExp("[ \r\n][ \r\n]*"));

    QFile f("../dojo.txt");
    f.open(QIODevice::ReadOnly);
    QString fileContent = QString(f.readAll());
    //qDebug() << "Content=" << fileContent;
    HttpRequest req("HTTP/1.0 200 Ok\r\n"
                   "Content-Type: text/html; charset=\"utf-8\"\r\n"
                   "\r\n" + fileContent
                   );

    client->sendRequest(req);
    client->close();
}



void HttpServer::connectClient(){
    HttpClient *client = new HttpClient(p_tcpServer->nextPendingConnection(), this);
    qDebug() << "HttpClient connected";
    connect(client, SIGNAL(requestReceived(HttpRequest)), this, SLOT(processRequest(HttpRequest)));
}


void HttpServer::disconnectClient()
{
    qDebug() << "httpClient disconnected";
}
